﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infinitus.Mail.Utilities.Helper;
using Infinitus.Mail.Core.Configuration;
using NLog;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.IO;
using SyncBingosoftUsers.Utiltiy;
using Bingosoft.WindowsService.Commander.Adapter;

namespace SyncBingosoftUsers
{
    public class SyncUser : ICommandAdapter
    {
        private Logger logger = LogManager.GetCurrentClassLogger();

        public void Start()
        {
            DCUser[] users = null;
            try
            {
                users = ADService.DCHelper.GetAll<DCUser>(DCItemType.User);
            }
            catch (Exception ex)
            {
                logger.ErrorException("从AD中获取用户时出错", ex);
                return;
            }

            logger.Debug("得到用户数:{0}", users.Length);

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultDB"].ConnectionString))
            {
                try
                {
                    conn.Open();
                }
                catch (Exception ex)
                {
                    logger.ErrorException("数据库打开时出错", ex);
                    return;
                }
                string sql = "INSERT INTO [dbo].[SyncUsers] ([Name],[LoginId],[Email],[ThumbnailPhoto],[MobilePhone]) VALUES "+
                    "(@Name,@LoginId,@Email,@ThumbnailPhoto,@MobilePhone)";

                new SqlCommand("delete from [dbo].[SyncUsers]", conn).ExecuteNonQuery();

                SqlCommand cmd = null;
                using (cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.Add(new SqlParameter("Name", System.Data.SqlDbType.NVarChar, 200));
                    cmd.Parameters.Add(new SqlParameter("LoginId", System.Data.SqlDbType.VarChar, 200));
                    cmd.Parameters.Add(new SqlParameter("Email", System.Data.SqlDbType.VarChar, 200));
                    cmd.Parameters.Add(new SqlParameter("MobilePhone", System.Data.SqlDbType.VarChar, 200));
                    cmd.Parameters.Add(new SqlParameter("ThumbnailPhoto", System.Data.SqlDbType.Image));

                    foreach (var u in users)
                    {
                        logger.Trace("准备插入用户：Name:{0} MobilePhone:{1} Email:{2} LoginId:{3} ThumbnailPhoto:{4}",
                            u.Name, u.Mobile, u.Email, u.AccountId, u.ThumbnailPhoto);

                        if (!string.IsNullOrEmpty(u.Name) && !string.IsNullOrEmpty(u.Mobile)
                            && !string.IsNullOrEmpty(u.Email) && !string.IsNullOrEmpty(u.AccountId))
                        {
                            cmd.Parameters["Name"].Value = u.Name;
                            cmd.Parameters["MobilePhone"].Value = u.Mobile;
                            cmd.Parameters["Email"].Value = u.Email;
                            cmd.Parameters["LoginId"].Value = u.AccountId;

                            if (u.ThumbnailPhoto == null)
                                cmd.Parameters["ThumbnailPhoto"].Value = DBNull.Value;
                            else
                                cmd.Parameters["ThumbnailPhoto"].Value = u.ThumbnailPhoto;

                            try
                            {
                                cmd.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                logger.ErrorException("插入用户信息时出错,跳过该用户", ex);
                            }
                        }
                    }

                    logger.Trace("用户插入完毕！");

                    using (cmd = new SqlCommand("usp_SyncUsers", conn))
                    {
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        try
                        {
                            logger.Trace("准备执行存储过程");
                            cmd.ExecuteNonQuery();
                            logger.Trace("准备执行存储完毕");
                        }
                        catch (Exception ex)
                        {
                            logger.ErrorException("执行存储过程出错", ex);
                        }
                    }
                }
                conn.Close();
            }

                //if (u.ThumbnailPhoto != null)
                //    Bytes2Image.ReturnPhoto(u.ThumbnailPhoto).Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images") + "\\" + u.AccountId + ".jpg");

        }

        public void Execute()
        {
            try
            {
                Start();
            }
            catch (Exception ex)
            {
                logger.ErrorException("Execute:", ex);
            }
        }

        public void Initialize(System.Xml.XmlNode config)
        {
            logger.Trace("定期更新用户信息已启动!");
        }

        public string Name
        {
            get { return "定期更新用户信息"; }
        }

        public void Dispose()
        {
            logger.Trace("定期更新用户信息已关闭!");
        }
    }
}
